package ch08
{
	import flash.display.Sprite;
	import flash.events.Event;

	import utils.Ball;

	/**
	 * 弹簧链.
	 * 将几个弹性小球串联起
	 * @author sjp
	 *
	 */
	public class Chain extends Sprite
	{
		private var ball0:Ball;
		private var ball1:Ball;
		private var ball2:Ball;
		private var spring:Number=0.1;
		//摩擦力
		private var friction:Number=0.8;
		//重力
		private var gravity:Number=5;

		private var balls:Array;
		private var numBalls:Number=5;

		public function Chain()
		{
			init();
		}

		private function init():void
		{
//			ball0=new Ball(20);
//			addChild(ball0);
//			ball1=new Ball(20);
//			addChild(ball1);
//			ball2=new Ball(20);
//			addChild(ball2);

			balls=new Array();
			for (var i:uint=0; i < numBalls; i++)
			{
				var ball:Ball=new Ball(20);
				addChild(ball);
				balls.push(ball);
			}
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}

		private function onEnterFrame(event:Event):void
		{
//			moveBall(ball0, mouseX, mouseY);
//			moveBall(ball1, ball0.x, ball0.y);
//			moveBall(ball2, ball1.x, ball1.y);
//			graphics.clear();
//			graphics.lineStyle(1);
//			graphics.moveTo(mouseX, mouseY);
//			graphics.lineTo(ball0.x, ball0.y);
//			graphics.lineTo(ball1.x, ball1.y);
//			graphics.lineTo(ball2.x, ball2.y);

			graphics.clear();
			graphics.lineStyle(1);
			graphics.moveTo(mouseX, mouseY);
			moveBall(balls[0], mouseX, mouseY);
			graphics.lineTo(balls[0].x, balls[0].y);
			for (var i:uint=1; i < numBalls; i++)
			{
				var ballA:Ball=balls[i - 1];
				var ballB:Ball=balls[i];
				moveBall(ballB, ballA.x, ballA.y);
				graphics.lineTo(ballB.x, ballB.y);
			}
		}

		private function moveBall(ball:Ball, targetX:Number, targetY:Number):void
		{
			ball.vx+=(targetX - ball.x) * spring;
			ball.vy+=(targetY - ball.y) * spring;
			ball.vy+=gravity;
			ball.vx*=friction;
			ball.vy*=friction;
			ball.x+=ball.vx;
			ball.y+=ball.vy;
		}
	}
}